<?php
class Order_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->model('User_model','user');
        $this->load->model('Address_model','address');
    }
    


    function insert($address,$goods)
    {
    	if(!$goods)
    		return false;
    	$amount = 0;
    	foreach($goods as $g)
    	{
    		$amount += $g['price'];
    	}  	
    	$this->db->trans_start();
    	$order = array(
        	'order_sn' => $this->createSN(),		
        	'user_id'	  =>  $this->user->getUserId(),
        	'order_status' => 0,
        	'consignee' => $address['consignee'],
        	'province' => $address['province'],
        	'city'       => $address['city'],
        	'address' => $address['address'],
        	'zipcode' => $address['zipcode'],
        	'mobile' => $address['mobile'],
        	'telephone' => $address['telephone'],
        	'price' => $amount,
        	'create_time' => time(),
        		
        );
        $this->db->insert('order', $order);
        $orderid = $this->db->insert_id();
        $order['id'] = $orderid;
        foreach($goods as $g)
        {
        	$data = array(
        		'order_id' => $orderid,
        		'goods_id'	=> $g['goods_id'],
        		'goods_name' => $g['goods_name'],
        		'market_price' => $g['market_price'],
        		'goods_thumb' => $g['goods_thumb'],
        		'buy_price' =>  $g['shop_price'],
        		'amount' =>  $g['sum'],       		
        	);
        	$this->db->insert('order_goods', $data);
        }
        $this->db->trans_complete();
        return $order;
    }

    
    function createSN()
    {
    	$this->db->query('SET auto_increment_increment=2012;');
    	$this->db->insert('sn',array('id'=>''));
    	return  date('Ymdhis').$this->db->insert_id();
    }
    
    function getOrder($sn)
    {
    	$query = $this->db->get_where('order',array('order_sn'=>$sn));
    	return $query->row_array();
    }
    
    function completePay($sn)
    {
    	$this->db->update('order', array('order_status'=>1),'order_status = 0 and order_sn = "'.$sn.'"');    	
    }

}